<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js"
import { Plus, Edit, Delete, Location } from '@element-plus/icons-vue'

// 路由实例
const router = useRouter()

// 地址列表数据
const addressList = ref([])
// 加载状态
const loading = ref(false)
// 用户ID
const userId = ref(null)
// 地址表单对话框显示状态
const dialogVisible = ref(false)
// 是否为编辑模式
const isEdit = ref(false)
// 地址表单数据
const addressForm = ref({
  id: null,
  userId: null,
  receiverName: '',
  receiverPhone: '',
  detailedAddress: '',
  isDefault: false
})
// 表单规则
const rules = ref({
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  detailedAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
})
// 表单引用
const addressFormRef = ref(null)

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'))
  if (!userInfo) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  userId.value = userInfo.id
  return true
}

// 获取地址列表
const getAddressList = async () => {
  if (!checkLoginStatus()) return
  
  loading.value = true
  try {
    const res = await request.get('/address/list', {
      params: { userId: userId.value }
    })
    if (res.code === 200) {
      addressList.value = res.data
    } else {
      ElMessage.error(res.message || '获取地址列表失败')
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  } finally {
    loading.value = false
  }
}

// 添加新地址
const addAddress = () => {
  if (!checkLoginStatus()) return
  
  isEdit.value = false
  addressForm.value = {
    userId: userId.value,
    receiverName: '',
    receiverPhone: '',
    detailedAddress: '',
    isDefault: false
  }
  dialogVisible.value = true
}

// 编辑地址
const editAddress = (row) => {
  if (!checkLoginStatus()) return
  
  isEdit.value = true
  addressForm.value = {
    id: row.id,
    userId: row.userId,
    receiverName: row.receiverName,
    receiverPhone: row.receiverPhone,
    detailedAddress: row.detailedAddress,
    isDefault: row.isDefault
  }
  dialogVisible.value = true
}

// 删除地址
const deleteAddress = async (id) => {
  if (!checkLoginStatus()) return
  
  try {
    await ElMessageBox.confirm('确定要删除这个地址吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete(`/address/delete/${id}`)
    if (res.code === 200) {
      ElMessage.success('删除地址成功')
      getAddressList()
    } else {
      ElMessage.error(res.message || '删除地址失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error('删除地址失败')
    }
  }
}

// 设置为默认地址
const setDefaultAddress = async (id) => {
  if (!checkLoginStatus()) return
  
  try {
    const res = await request.put('/address/set-default', null, {
      params: { id, userId: userId.value }
    })
    if (res.code === 200) {
      ElMessage.success('设置默认地址成功')
      getAddressList()
    } else {
      ElMessage.error(res.message || '设置默认地址失败')
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    ElMessage.error('设置默认地址失败')
  }
}

// 提交地址表单
const submitAddressForm = async () => {
  if (!addressFormRef.value) return
  
  await addressFormRef.value.validate(async (valid) => {
    if (!valid) {
      return false
    }
    
    try {
      let res
      if (isEdit.value) {
        res = await request.put('/address/update', addressForm.value)
      } else {
        res = await request.post('/address/add', addressForm.value)
      }
      
      if (res.code === 200) {
        ElMessage.success(isEdit.value ? '更新地址成功' : '添加地址成功')
        dialogVisible.value = false
        getAddressList()
      } else {
        ElMessage.error(res.message || (isEdit.value ? '更新地址失败' : '添加地址失败'))
      }
    } catch (error) {
      console.error(isEdit.value ? '更新地址失败:' : '添加地址失败:', error)
      ElMessage.error(isEdit.value ? '更新地址失败' : '添加地址失败')
    }
  })
}

// 页面加载时获取地址列表
onMounted(() => {
  getAddressList()
})
</script>

<template>
  <div class="address-container">
    <el-card class="address-card">
      <div class="address-header">
        <h2>收货地址管理</h2>
        <el-button type="primary" @click="addAddress" :icon="Plus">添加新地址</el-button>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="addressList.length === 0" class="empty-container">
        <el-empty description="您还没有添加任何收货地址" />
      </div>

      <div v-else class="address-list">
        <el-card 
          v-for="item in addressList" 
          :key="item.id" 
          class="address-item"
          :class="{ 'is-default': item.isDefault }"
        >
          <div class="address-item-header">
            <div class="receiver-info">
              <span class="receiver-name">{{ item.receiverName }}</span>
              <span class="receiver-phone">{{ item.receiverPhone }}</span>
              <el-tag v-if="item.isDefault" type="success" size="small">默认地址</el-tag>
            </div>
            <div class="address-actions">
              <el-button 
                v-if="!item.isDefault" 
                type="success" 
                size="small" 
                :icon="Location" 
                @click="setDefaultAddress(item.id)"
              >
                设为默认
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                :icon="Edit" 
                @click="editAddress(item)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                :icon="Delete" 
                @click="deleteAddress(item.id)"
              >
                删除
              </el-button>
            </div>
          </div>
          <div class="address-detail">
            {{ item.detailedAddress }}
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 地址表单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑收货地址' : '添加收货地址'"
      width="500px"
      @closed="addressFormRef?.resetFields()"
    >
      <el-form 
        ref="addressFormRef"
        :model="addressForm"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="addressForm.receiverName" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="receiverPhone">
          <el-input v-model="addressForm.receiverPhone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input 
            v-model="addressForm.detailedAddress" 
            type="textarea" 
            rows="3"
            placeholder="请输入详细地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="默认地址">
          <el-switch v-model="addressForm.isDefault"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddressForm">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.address-container {
  padding: 20px;
}

.address-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.address-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.loading-container,
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.address-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.address-item {
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.address-item:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.address-item.is-default {
  border: 1px solid #67c23a;
  box-shadow: 0 0 8px rgba(103, 194, 58, 0.2);
}

.address-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

.receiver-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.receiver-name {
  font-weight: bold;
  font-size: 16px;
}

.receiver-phone {
  color: #606266;
}

.address-actions {
  display: flex;
  gap: 5px;
  margin-top: 10px;
}

.address-detail {
  color: #606266;
  line-height: 1.5;
  word-break: break-all;
  padding: 5px 0;
}

@media (max-width: 768px) {
  .address-list {
    grid-template-columns: 1fr;
  }
  
  .address-item-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .address-actions {
    margin-top: 10px;
    width: 100%;
    justify-content: flex-end;
  }
}
</style>